import cTitle from "components/title";
import { Toast } from 'vant';
import cCalendar from "components/calendar";

export default {
  data() {
    return {
      calendarEvents: [],
      currentTime: "12:00",
      isRest: false,
      today: "",
      show1: false,  // 编辑时间
      showDay: false, // 按天添加时间
      showTime: false, // 选择时间
      showDefault: false,  // 添加默认时间
      chooseStore: {},
      default_time: [],
      day_time: [],
      choose_start: "",
      choose_end: "",
      start: false,
      isDefault: 0,
      period_id: "",
      from: "",
      isChange: false,
      id: "",
      aplly_for: 1,//1-未通过审核、2-通过审核、-1驳回审核

    };
  },
  activated() {

    this.initData();
    this.today = new Date().getFullYear() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getDate();
    console.log(this.$route);
    if (this.$route.params.aid) {
      this.id = this.$route.params.aid;
      this.getData();
      this.getTimeList(new Date(`${this.today} 00:00:00`).getTime() / 1000);
      this.getDefault();
    }
    this.aplly_for = this.$route.params.aplly_for;
    if (this.$route.params.aplly_for == 1) {
      let work_time = JSON.parse(sessionStorage.getItem('work_time'))
      if (work_time) {
        this.default_time = work_time
      }
    }

  },
  methods: {
    initData() {
      this.calendarEvents = [];
      this.currentTime = "12:00";
      this.isRest = false;
      this.today = "";
      this.show1 = false;  // 编辑时间
      this.showDay = false; // 按天添加时间
      this.showTime = false; // 选择时间
      this.showDefault = false;  // 添加默认时间
      this.chooseStore = {};
      this.default_time = [];
      this.day_time = [];
      this.choose_start = "";
      this.choose_end = "";
      this.start = false;
      this.isDefault = 0;
      this.isChange = false;
    },
    //将时间戳转换成正常时间格式
    timestampToTime(timestamp) {
      if (!Number(timestamp) || timestamp == "") {
        return "";
      }
      let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "-";
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());
      return Y + M + D;
    },
    getData() {
      $http.get("plugin.be-within-call.frontend.work-time.group", { aid: this.$route.params.aid }, '').then(res => {
        if (res.result) {
          if (res.result === 1) {
            let _arr = [];
            for (let item of res.data) {
              _arr.push(this.timestampToTime(item.date));
              this.calendarEvents = _arr;
            }
          } else {
            this.$toast(res.msg);
          }
        } else {
          this.$toast(res.msg);
        }
      })
    },
    editTime() {
      this.showDefault = false;
      this.show1 = true;
    },
    clearTime() {
      this.show1 = false;
      this.choose_start = "";
      this.choose_end = "";
    },
    addDefaultTime() {
      this.showDefault = true;
      this.isDefault = 1;
    },
    addTime() {
      this.showDay = true;
      this.isDefault = 2;
    },
    confirmTime(e) {
      this.start ? this.choose_start = e : this.choose_end = e;
      console.log(this.choose_start, "choose_start");
      console.log(this.choose_end, "choose_end");
      if (!this.start) {

      }
      this.showTime = false;
    },
    selectedDay(e) {
      if (this.$route.params.aplly_for == 1) {
        this.today = `${e[0]}/${e[1]}/${e[2]}`;
      } else {
        let format_time = `${e[0]}/${e[1]}/${e[2]}`;
        this.today = format_time;
        this.getTimeList(new Date(`${format_time} 00:00:00`).getTime() / 1000);
      }
    },
    getDefault() {
      $http.get("plugin.be-within-call.frontend.work-time.date-time", { aid: this.id, date:0 }, '').then((response) => {
        if (response.result === 1) {
          let arr = response.data;
          console.log(arr,"arr===");
          arr.forEach((item) => {
            item.work_hour_start = item.start_at;
            item.work_hour_end = item.finish_at;
          })
          let _filter_result = arr.filter(item => {
            if (item.date == 0) {
              return item;
            }
          })
          this.default_time = _filter_result;
        } else {
          this.$toast(response.msg);
        }

      })
  },
  // 选择预约指定时间
  getTimeList(date) {
    $http.get("plugin.be-within-call.frontend.work-time.date-time", { aid: this.id, date }, '').then((response) => {
      if (response.result === 1) {
        let arr = response.data;
        if (arr && arr.length !== 0) {
          for (let i = 0; i < arr.length; i++) {
            arr[i].work_hour_start = arr[i].start_at;
            arr[i].work_hour_end = arr[i].finish_at;
            arr[i].need_rest == 1 ? arr[i].status = false : arr[i].status = true;
          }
          let arr_every = arr.every(item => {
            return item.need_rest == 1;
          })
          if (arr_every) {
            this.isRest = false;
          } else {
            this.isRest = true;
          }
          this.day_time = arr;

        }else{
          this.day_time = [];
          this.isRest = false;
        }

      } else {
        this.$toast(response.msg);
      }
      // this.popup_show = true;
      // this.showCalendar = true;
    },
      function (response) {
        console.log(response);
      }
    );
  },
  chooseTime(str, time) {
    str === "start" ? this.start = true : this.start = false;
    if (time) {
      this.currentTime = time;
    }
    this.showTime = true;
  },
  choose(item) {
    this.chooseStore = item;
    this.getDefaultTime();  // 获取门店默认工作时间
    this.getAllService();   // 获取门店全部预约时间
    this.getService();     // 获取门店今天预约时间
  },
  getDefaultTime() {
    $http
      .get(
        "plugin.appointment.frontend.work-time.get-default-period",
        { store_id: this.chooseStore.id, worker_id: this.worker_id },
        "获取中"
      )
      .then(response => {
        if (response.result === 1) {
          this.default_time = response.data;
        } else {
          Toast(response.msg);
        }
      })
      .catch(err => {
        console.log(err);
      });
  },
  getService() {
    $http
      .get(
        "plugin.appointment.frontend.work-time.get-period-list-by-date",
        { store_id: this.chooseStore.id, worker_id: this.worker_id, work_date: this.today },
        "获取中"
      )
      .then(response => {
        if (response.result === 1) {
          for (let i = 0; i < response.data.period_list.length; i++) {
            response.data.period_list[i].status == 1 ? response.data.period_list[i].status = false : response.data.period_list[i].status = true;
          }
          this.day_time = response.data.period_list;
          response.data.worker_status == 1 ? this.isRest = false : this.isRest = true;
        } else {
          Toast(response.msg);
        }
      })
      .catch(err => {
        console.log(err);
      });
  },
  getAllService() {
    $http
      .get(
        "plugin.appointment.frontend.work-time.get-worker-dates-by-store-id",
        { store_id: this.chooseStore.id, worker_id: this.worker_id },
        "获取中"
      )
      .then(response => {
        if (response.result === 1) {

          response.data.forEach((item) => {
            item.work_hour_start = item.min_time;
            item.work_hour_end = item.max_time;
          })
          console.log(response.data);
          this.default_time = response.data;
          console.log(this.default_time);
          this.calendarEvents = response.data.map(item => {
            if (item.work_status == 1) {
              return item.work_date_format + "-休";
            } else {
              return item.work_date_format;
            }
          });
        } else {
          Toast(response.msg);
        }
      })
      .catch(err => {
        console.log(err);
      });
  },
  deleteTimeAll(){
    let today_time = new Date(`${this.today} 00:00:00`).getTime() / 1000;
    let json = { aid: this.id,date:today_time }

    $http
      .get("plugin.be-within-call.frontend.work-time.day-del", json, "获取中").then(response => {
        if (response.result === 1) {
          this.getTimeList(today_time);
          this.getData()
          Toast(response.msg);
        } else {
          Toast(response.msg);
        }
      })
      .catch(err => {
        console.log(err);
      });
  },
  deleteTimeWork(data){
    $http.post("plugin.be-within-call.frontend.work-time.del",{wid:data.id}).then(res=>{
      this.$toast(res.msg);
      if(res.result){
          this.getData();
          this.getTimeList(new Date(`${this.today} 00:00:00`).getTime() / 1000);
      }
    })
  },
  deleteTime(data) {
    console.log(this.isDefault,"this.isDefault");
    if (this.aplly_for == 1) {
      return;
    }
     $http.post("plugin.be-within-call.frontend.work-time.del",{wid:data.id}).then(res=>{
        this.$toast(res.msg);
        if(res.result){
          this.getDefault();
        }
      })
  },
  submitTime() {
    if (this.choose_start == "" && this.choose_end == '') {
      return this.$toast("请选择时间")
    } else if (!this.choose_start) {
      return this.$toast("请选择开始时间")
    } else if (!this.choose_end) {
      return this.$toast("请选择结束时间")
    } else if (this.choose_start.split(':')[0] > this.choose_end.split(':')[0]) {
      return this.$toast("结束时间必须大于开始时间")
    } else if (this.choose_start.split(':')[0] == this.choose_end.split(':')[0]) {
      let start_time = Number(this.choose_start.split(':')[1]), end_time = Number(this.choose_end.split(':')[1])
      if (start_time == end_time) {
        return this.$toast("结束时间不能等于开始时间")
      } else if (String(start_time / 10).indexOf('.') > -1) {
        return this.$toast("时间间隔为10分钟")
      } else {
        if (end_time - 10 < start_time) {
          return this.$toast("时间间隔为10分钟")
        }
      }
    }
    if (this.aplly_for == 1) {

      this.default_time.push({ work_hour_start: this.choose_start, work_hour_end: this.choose_end })
      this.show1 = false;
      sessionStorage.setItem("work_time_today", JSON.stringify(this.today))
      sessionStorage.setItem("work_time", JSON.stringify(this.default_time))


      return false;
    }


    let json = {};
    let url = "";


    if (this.isDefault === 1) {
      // 添加默认时间
      url = "plugin.be-within-call.frontend.work-time.add-default";
      json = {
        aid: this.id,
        start_at: new Date(`${this.today} ${this.choose_start}:00`).getTime() / 1000,
        finish_at: new Date(`${this.today} ${this.choose_end}:00`).getTime() / 1000,
      };
    } else {
      // 按天添加时间
      url = 'plugin.be-within-call.frontend.work-time.create';
      json = {
        start_at: new Date(`${this.today} ${this.choose_start}:00`).getTime() / 1000,
        finish_at: new Date(`${this.today} ${this.choose_end}:00`).getTime() / 1000,
        aid: this.id
      };
    }
    $http
      .post(url, json, "获取中")
      .then(response => {
        Toast(response.msg);
        if (response.result === 1) {
          this.show1 = false;
          this.choose_start = "";
          this.choose_end = "";
          // this.getDefaultTime();
          if(this.isDefault === 1){
            this.getDefault();
          }else{
            this.getTimeList(new Date(`${this.today} 00:00:00`).getTime() / 1000);
            this.getData();
          }
        }
      })
      .catch(err => {
        console.log(err);
      });
  },
  changeStatus(item, str) {
    let need_rest = 1;
    str ? need_rest = 0 : need_rest = 1;
    if (!this.isChange) {
      this.isChange = true;
      $http
        .get(
          "plugin.be-within-call.frontend.work-time.rest",
          { wid: item.id, need_rest },
          "获取中"
        )
        .then(response => {
          if (response.result === 1) {
            this.getTimeList(new Date(`${this.today} 00:00:00`).getTime() / 1000);
          } else {
            Toast(response.msg);
          }
          setTimeout(() => {
            this.isChange = false;
          }, 1000);
        })
        .catch(err => {
          this.isChange = false;
          console.log(err);
        });
    }
  },
  changeDayStatusMain() {
    let need_rest = this.isRest ? 0 : 1;
    $http.post('plugin.be-within-call.frontend.work-time.rest', { need_rest, aid: this.id, date: new Date(`${this.today} 00:00:00`).getTime() / 1000 }, '').then(res => {
      this.$toast(res.msg);
      if (res.result) {
        this.getData();
        this.getTimeList(new Date(`${this.today} 00:00:00`).getTime() / 1000);
      }
    })
  },
},
components: { cTitle, cCalendar }
};
